import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { getRiotData, postRiotData, getImg } from './utils/res.js'
import icon from '../../resources/icon.png?asset'
const fs = require('fs');
// 禁用https证书验证
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // 窗口大小是否可以被调整
    resizable: false,
    // 窗口是否可以最大化
    maximizable: false,
    minimizable: false,
    // 无边框
    frame: false,
    // 窗口背景透明
    transparent: true,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
      nodeIntegration: true,
      contextIsolation: false,
      // 关闭win后台节流效率模式
      backgroundThrottling: false
    }
  })

  //重点在下面这行，开启调试
  mainWindow.webContents.openDevTools()

  // 软件右上角功能区
  const operation = {
    minimize: () => {
      mainWindow.focus();
      mainWindow.minimize();
    },
    close: () => {
      mainWindow.destroy();
    },
  };
  ipcMain.on('detach:vue', async (event, arg) => {
    operation[arg.type]();
    console.log(arg.type);
  });

  let key = {}
  // 获取玩家信息
  ipcMain.on('getUserInfo:vue', async (event, arg) => {
    key = arg.key
    try {
      const currentUser = await getRiotData('/lol-summoner/v1/current-summoner', key);
      const data = JSON.parse(currentUser)
      event.returnValue = data
    } catch (error) {
      console.log(error);
      const data = 'getUserInfoError'
      event.returnValue = data
    }
  })

  // 获取用户头像
  ipcMain.on('getUserImg:vue', async (event, arg) => {
    try {
      const currentUser = await getImg('/lol-game-data/assets/v1/profile-icons/' + arg.profileIconId + '.jpg', key);
      const data = currentUser
      event.returnValue = data
    } catch (error) {
      console.log(error);
      const data = 'getUserImgError'
      event.returnValue = data
    }
  })

  // 获取玩家单双排/灵活组排数据
  ipcMain.on('getRankedData:vue', async (event, arg) => {
    try {
      const currentUser = await getRiotData('/lol-ranked/v1/current-ranked-stats', key);
      const data = JSON.parse(currentUser)
      event.returnValue = data
    } catch (error) {
      console.log(error);
      const data = 'getRankedDataError'
      event.returnValue = data
    }
  })

  // 获取玩家历史战绩(20局)
  ipcMain.on('getMatchHistory:vue', async (event, arg) => {
    try {
      const currentUser = await getRiotData('/lol-match-history/v1/products/lol/' + arg.puuid + '/matches', key);
      const data = JSON.parse(currentUser)
      event.returnValue = data
    } catch (error) {
      console.log(error);
      const data = 'getMatchHistoryError'
      event.returnValue = data
    }
  })

  let state = ''
  // 获取玩家当前状态
  ipcMain.on('getUserState:vue', async (event, arg) => {
    try {
      const currentUser = await getRiotData('/lol-gameflow/v1/gameflow-phase', key);
      const data = JSON.parse(currentUser)
      if (data !== state) {
        state = data
        console.log(state);
        // 不一定要返回数据给渲染进程
        mainWindow.webContents.send('getUserState:server', { state });
      }
    } catch (error) {
      state = 'offline'
      mainWindow.webContents.send('getUserStateError:server', { state });
    }
  })

  // 接受对局
  ipcMain.on('acceptMatch:vue', async (event, arg) => {
    console.log('接受对局');
    try {
      await postRiotData('/lol-matchmaking/v1/ready-check/accept', null, 'POST', key);
      console.log('接受对局成功!');
      // event.returnValue = 'acceptMatchSuccess'
    } catch (error) {
      console.log('接受对局失败!');
      console.log(error);
      // event.returnValue = 'acceptMatchError'
    }
  })

  // 选择英雄确定
  ipcMain.on('getActionId:vue', async (event, arg) => {
    try {
      const currentUser = await getRiotData('/lol-champ-select/v1/session', key);
      const data = JSON.parse(currentUser)
      event.returnValue = data
    } catch (error) {
      event.returnValue = 'getActionIdError'
    }
  })
  ipcMain.on('selectChamp:vue', async (event, arg) => {
    try {
      await postRiotData('/lol-champ-select/v1/session/actions/' + arg.params.actionId, arg.params, 'PATCH', key);
      console.log('选择英雄成功');
      event.returnValue = 'selectChampSuccess'
    } catch (error) {
      console.log('选择英雄失败');
      console.log(error);
      event.returnValue = 'selectChampError'
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 关闭电脑硬件GPU加速,解决有些电脑打不开软件的问题
app.commandLine.appendSwitch("--in-process-gpu");

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

